<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="基本信息" name="first">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="18">
              <el-form-item label="试卷名称" prop="paperName">
                <el-input
                  v-model="form.paperName"
                  placeholder="请输入试卷名称"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="学科" prop="subjectId">
                <!--  <el-input v-model="form.subjectId" placeholder="请输入学科id" /> -->
                <el-select
                  clearable
                  v-model="form.subjectId"
                  placeholder="请选择学科"
                >
                  <el-option
                    v-for="item in subjectList"
                    :key="item.subjectId"
                    :label="item.subjectName"
                    :value="item.subjectId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="时长:分钟" prop="suggestTime">
                <el-input-number
                  v-model="form.suggestTime"
                  placeholder="请输入建议时长"
                  :min="1"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="开始时间" prop="limitStartTime">
                <el-date-picker
                  type="datetime"
                  clearable
                  v-model="form.limitStartTime"
                  placeholder="请选择开始时间"
                >
                </el-date-picker>
              </el-form-item> </el-col
            ><el-col :span="8">
              <el-form-item label="结束时间" prop="limitEndTime">
                <el-date-picker
                  type="datetime"
                  clearable
                  v-model="form.limitEndTime"
                  placeholder="请选择结束时间"
                >
                  <!-- 
                  value-format="yyyy-MM-dd HH:mm:ss" -->
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="选择题目" name="second">
        <el-button type="success" @click="openDialog">手动选择题目</el-button>
        <el-button type="primary" @click="randomQuestion"
          >随机选择题目</el-button
        >
        <el-card class="mt10" v-show="questions.length != 0">
          <show-question :questions="questions"></show-question>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <div style="margin-top: 20px">
      <el-button type="primary" @click="submitForm">确认</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <el-dialog :visible.sync="open" destroy-on-close>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="108px"
      >
        <el-form-item label="题目名称" prop="questionTitle">
          <el-input
            v-model="queryParams.questionTitle"
            placeholder="请输入题目名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="题目类型" prop="questionType">
          <el-select
            clearable
            v-model="queryParams.questionType"
            placeholder="请选择题目类型"
          >
            <el-option
              v-for="dict in dict.type.exam_question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学科" prop="subjectId">
          <el-select
            clearable
            v-model="queryParams.subjectId"
            placeholder="请选择学科"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.subjectId"
              :label="item.subjectName"
              :value="item.subjectId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :border="true"
        v-loading="loading"
        :data="questionList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" />
        <!--         <el-table-column label="主键" align="center" prop="questionId" /> -->
        <el-table-column label="标题" align="center" prop="questionTitle">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.questionTitle"
              placement="right"
            >
              <!-- TODO 题干如果是HTML标签选中 -->
              <span> {{ scope.row.questionTitle | ellipsis(0, 5) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" prop="questionType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.exam_question_type"
              :value="scope.row.questionType"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="分数"
          sortable
          align="center"
          prop="questionScore"
        />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[8, 20, 50, 100]"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getQuestionList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">选择</el-button>
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addPaper } from "@/api/exam/paper";
import showQuestion from "@/components/exam/showQuestion";
import { listSubject } from "@/api/exam/subject";
import { listQuestion } from "@/api/exam/question";
import { mapActions, mapGetters } from "vuex";
export default {
  dicts: ["exam_question_type"],
  name: "addPaper",
  components: { showQuestion },
  data() {
    return {
      activeName: "first",
      open: false,
      loading: true,
      // 选中数组，
      ids: [],
      // 非单个禁用
      single: true,
      // 题目表格数据
      questionList: [],
      // 总条数
      total: 0,
      // 查询题目参数
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        // 题目名称
        questionTitle: null,
        // 题目类型
        questionType: null,
        subjectId: null,
      },
      // 非多个禁用
      multiple: true,
      //  学科列表
      subjectList: [],
      // insertPaper 表单参数
      form: {
        //   暂定只有限时考试 ，写死
        paperType: "2",
        paperName: "",
        isRandomQuesiont: false,
        subjectId: null,
        paperScore: 0,
        questionCount: 0,
        suggestTime: 60,
        limitStartTime: "",
        limitEndTime: "",
      },
      // 表单校验
      rules: {
        paperName: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" },
          {
            max: 100,
            message: "试卷名称超过100个字符",
            trigger: "blur",
          },
        ],
        suggestTime: [
          { required: true, message: "建议市场不能为空", trigger: "blur" },
        ],
        limitStartTime: [
          {
            required: true,
            message: "时段试卷 开始时间不能为空",
            trigger: "blur",
          },
        ],
        limitEndTime: [
          {
            required: true,
            message: "时段试卷 结束时间不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getSubjectList();
  },

  computed: {
    // ...mapGetters(["questions"]),
    questions: function () {
      return this.$store.state.questions.questions;
    },
  },
  beforeDestroy() {
    console.log("beforeDestroy");
    // 避免用户在选题但是没创建，离开去其他路由时，vuex还有数据
    this.delAllQuestions();
  },
  destroy() {},
  methods: {
    ...mapActions(["setQuestions", "delAllQuestions", "getQuestionScore"]),

    setPaperScore() {
      this.form.paperScore = this.questions.reduce((pre, next) => {
        return pre + parseInt(next.questionScore);
      }, 0);
    },
    setPaperScore() {
      this.form.questionCount = this.questions.length;
    },

    // 用户选择好后，最终点击dialig的确认按钮关闭时，才赋值
    confirm() {
      this.open = false;
      // vuex
      this.setQuestions(this.ids);
      this.getQuestionScore();
    },
    /**关闭dialog */
    closeDialog() {
      this.open = false;
      this.ids = [];
    },
    openDialog() {
      this.ids = [];
      this.getQuestionList();
      this.loading = false;
      this.open = true;
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getQuestionList();
    },
    /** 重置问题列表搜索中按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 问题列表多选框选中数据
    handleSelectionChange(selection) {
      // 单独一个变量来存 最终用户选中取消后的最终数据
      this.ids = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查询学科列表 */
    async getSubjectList() {
      try {
        let { data } = await listSubject(this.queryParams);
        this.subjectList = data.records;
      } catch (error) {
        console.log(error);
        this.$modal.error("获取学科列表失败");
      }
    },

    /** 查询题目列表 */
    async getQuestionList() {
      this.loading = true;
      try {
        let { data } = await listQuestion(this.queryParams);
        this.questionList = data.records;
        this.total = data.total;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$modal.msgError("获取题目列表失败");
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    //TODO  随机选题
    randomQuestion() {
      this.isRandomQuesiont = true;
    },
    // 表单重置
    reset() {
      this.form = {
        paperType: "2",
        orderNum: null,
        paperName: "",
        subjectId: null,
        paperScore: 0,
        questionCount: 0,
        suggestTime: 60,
        limitStartTime: null,
        limitEndTime: null,
        // 状态（0正常 1停用）
        status: "0",
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (this.questions.length <= 0) {
            this.$modal.msgError("请选择题目");
            this.activeName = "second";
            return;
          }

          let questionIds = this.questions.map((e) => e.questionId);
          let data = Object.assign(this.form, {
            questionIds,

            limitStartTime: new Date(this.form.limitStartTime).valueOf(),

            limitEndTime: new Date(this.form.limitEndTime).valueOf(),

            paperScore: this.exam.questionsScore,
            questionCount: this.exam.questions.length,
          });
          await addPaper(data);
          // 提交以后，一定要记得清理vux
          this.delAllQuestions();
          this.$router.push({
            path: "/paper/list",
          });
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.showQuestion {
  margin-top: 20px;
  max-height: 32vh;
  overflow-y: auto;
  div {
    margin: 0 50px;
    i {
      margin-right: 20px;
    }
  }
}
</style>
